﻿using MultiDAQ_Analysis.Model;
using MultiDAQ_Analysis.Util;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using static UltraHighPerformanceChannelParser;


/// <summary>
/// 解析后的帧数据结构
/// </summary>
public class ParsedFrameData
{
    public ParsedChannelData[] Channels;
    public int ChannelCount;
    public long ParseTimeTicks;
    public int TotalSamples;
    public bool IsHighEndVersion;
}


/// <summary>
/// 内存安全版本的高性能多通道数据解析器
/// </summary>
public class UltraHighPerformanceChannelParser : IDisposable
{
    #region 常量定义
    /// <summary>
    /// 获取解析器是否正在运行
    /// </summary>
    public bool IsRunning => _isRunning && !_disposed;

    private const byte FRAME_HEADER = 0x5A;
    private const byte FRAME_TAIL_BYTE1 = 0x0D;
    private const byte FRAME_TAIL_BYTE2 = 0x0A;
    private const int MIN_CHANNEL = 1;
    private const int MAX_CHANNEL = 8;
    private const int HEADER_SIZE = 2;
    private const int SAMPLE_SIZE = 2;
    private const int TAIL_SIZE = 2;
    private const int STATISTICS_SIZE = 4;
    private const int ADC_BITS = 16;
    private const double VOLTAGE_RANGE = 3.0;
    private const int DEFAULT_SAMPLE_RATE = 2000000;
    private const int ADC_MAX_VALUE = 16384;   // 新增

    private const int BATCH_SIZE = 1024;
    private const int BASE_QUEUE_CAPACITY = 10000;
    private const int RESULT_QUEUE_CAPACITY = 50000;
    private const int STATS_REPORT_INTERVAL = 20000;
    #endregion

    #region 安全数据结构
    [StructLayout(LayoutKind.Sequential)]
    public struct AdcSample
    {
        public ushort RawValue;
        public float Voltage;
        public long TimestampTicks;
        public int SampleIndex;
    }

    /// <summary>
    /// 解析后的通道数据（重命名避免与配置模型冲突）
    /// </summary>
    public class ParsedChannelData
    {
        public int ChannelNumber;
        public uint Statistics;
        public int SampleCount;
        public AdcSample[] Samples;
        public long TimestampTicks;
        public bool IsEmpty;

        public ParsedChannelData()
        {
            Samples = new AdcSample[0];
        }
    }
    #endregion

    #region 动态线程管理字段
    private readonly int _minThreads;
    private readonly int _maxThreads;
    private volatile int _currentThreadCount;
    private readonly object _threadManagementLock = new object();
    private readonly CancellationTokenSource _cancellationTokenSource;
    private Thread _performanceMonitorThread;
    #endregion

    #region 核心字段
    private readonly ConcurrentQueue<byte[]> _dataQueue;
    private readonly ConcurrentQueue<ParsedFrameData> _resultQueue;
    private Thread[] _parseThreads;
    private volatile bool _isRunning;
    private volatile bool _disposed = false;
    private readonly object _disposeLock = new object();

    // 性能监控
    private long _totalProcessedFrames;
    private long _totalProcessedSamples;
    private long _totalProcessedBytes;
    private long _totalErrors;
    private long _startTimeTicks;
    private long _lastStatsTimeTicks;

    private long _lastProcessedFrames;
    private DateTime _lastMonitorTime;
    private readonly Queue<double> _recentProcessingRates = new Queue<double>();
    private volatile int _currentQueueCapacity = BASE_QUEUE_CAPACITY;

    private readonly double _lsb;
    private readonly double _sampleIntervalTicks;
    private readonly float _lsbFloat;

    public bool IsHighEndVersion { get; set; } = true;
    public readonly bool[] SelectedChannels = new bool[MAX_CHANNEL + 1];

    // 性能监控相关
    private readonly Stopwatch _performanceStopwatch = new Stopwatch();
    private long _lastPerformanceCheck;
    #endregion

    #region 构造函数
    public UltraHighPerformanceChannelParser(int minThreads = 1, int maxThreads = 0)
    {
        _minThreads = Math.Max(1, minThreads);
        _maxThreads = maxThreads <= 0 ? Environment.ProcessorCount : Math.Min(maxThreads, Environment.ProcessorCount);
        _currentThreadCount = _minThreads;
        _cancellationTokenSource = new CancellationTokenSource();

        _dataQueue = new ConcurrentQueue<byte[]>();
        _resultQueue = new ConcurrentQueue<ParsedFrameData>();
        _parseThreads = new Thread[_maxThreads];

        _lsb = VOLTAGE_RANGE / ADC_MAX_VALUE;
        _lsbFloat = (float)_lsb;
        _sampleIntervalTicks = TimeSpan.TicksPerSecond / (double)DEFAULT_SAMPLE_RATE;

        for (int i = MIN_CHANNEL; i <= MAX_CHANNEL; i++)
        {
            SelectedChannels[i] = true;
        }

        _startTimeTicks = DateTime.UtcNow.Ticks;
        _lastStatsTimeTicks = _startTimeTicks;
        _lastMonitorTime = DateTime.UtcNow;

        if (AppConfig.LogPrint == 1)
        {
            Console.WriteLine("解析器配置信息:");
            Console.WriteLine($"  电压范围: 0V ~ {VOLTAGE_RANGE}V");
            Console.WriteLine($"  ADC位数: {ADC_BITS}位 (0 ~ {(1 << ADC_BITS) - 1})");
            Console.WriteLine($"  LSB值: {_lsb:F8}V");
            Console.WriteLine($"  采样率: {DEFAULT_SAMPLE_RATE} Hz");
            Console.WriteLine($"  IsHighEndVersion: {IsHighEndVersion}");
            Console.WriteLine($"  选中通道: {string.Join(",", SelectedChannels.Select((selected, i) => selected ? i.ToString() : null).Where(s => s != null))}");
            Console.WriteLine($"[解析器初始化] 解析器已创建，最小线程: {_minThreads}, 最大线程: {_maxThreads}");
        }
    }
    #endregion

    #region 公共方法
    public void Start()
    {
        if (_isRunning) return;

        _isRunning = true;
        _startTimeTicks = DateTime.UtcNow.Ticks;
        _lastMonitorTime = DateTime.UtcNow;
        _performanceStopwatch.Start();

        StartParseThreads(_minThreads);

        _performanceMonitorThread = new Thread(PerformanceMonitorLoop)
        {
            IsBackground = true,
            Name = "PerformanceMonitor",
            Priority = ThreadPriority.BelowNormal
        };
        _performanceMonitorThread.Start();

        if (AppConfig.LogPrint == 1)
        {
            Console.WriteLine($"[解析器启动] 解析器已启动，初始线程数: {_currentThreadCount}");
        }
    }

    public void Stop()
    {
        if (!_isRunning) return;

        _isRunning = false;
        _cancellationTokenSource.Cancel();

        if (AppConfig.LogPrint == 1)
        {
            Console.WriteLine($"[停止] 正在停止解析器...");
        }

        for (int i = 0; i < _maxThreads; i++)
        {
            _parseThreads[i]?.Join(2000);
        }

        _performanceMonitorThread?.Join(1000);
        _performanceStopwatch.Stop();

        if (AppConfig.LogPrint == 1)
        {
            PrintFinalStats();
            Console.WriteLine($"[停止] 解析器已停止");
        }
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public void EnqueueData(byte[] data, int length)
    {
        if (data == null || length <= 0 || !_isRunning) return;

        byte[] dataCopy = new byte[length];
        Array.Copy(data, 0, dataCopy, 0, length);
        _dataQueue.Enqueue(dataCopy);

        // 统计接收的字节数
        Interlocked.Add(ref _totalProcessedBytes, length);

        int currentCount = _dataQueue.Count;
        if (currentCount > _currentQueueCapacity)
        {
            int dropCount = Math.Min(currentCount / 4, 2000);
            for (int i = 0; i < dropCount && _dataQueue.TryDequeue(out _); i++)
            {
                Interlocked.Increment(ref _totalErrors);
            }
        }
    }

    public bool TryGetResult(out ParsedFrameData result)
    {
        return _resultQueue.TryDequeue(out result);
    }

    public List<VoltagePoint> GetVoltagePoints()
    {
        var voltagePoints = new List<VoltagePoint>();

        while (TryGetResult(out var frameData))
        {
            if (frameData?.Channels != null)
            {
                foreach (var channel in frameData.Channels)
                {
                    if (!channel.IsEmpty && channel.Samples != null)
                    {
                        for (int j = 0; j < channel.SampleCount && j < channel.Samples.Length; j++)
                        {
                            var sample = channel.Samples[j];
                            voltagePoints.Add(new VoltagePoint(
                                new DateTime(sample.TimestampTicks),
                                sample.Voltage,
                                sample.SampleIndex,
                                $"Channel{channel.ChannelNumber}"
                            ));
                        }
                    }
                }
            }
        }

        return voltagePoints;
    }

    public void LoadChannelThresholds(List<ChannelData> channelDataList)
    {
        if (AppConfig.LogPrint == 1)
        {
            Console.WriteLine($"[解析器] 已加载{channelDataList.Count}个通道的阈值配置");
        }
    }
    #endregion

    #region 动态线程管理
    private void StartParseThreads(int count)
    {
        lock (_threadManagementLock)
        {
            for (int i = 0; i < count && i < _maxThreads; i++)
            {
                if (_parseThreads[i] == null || !_parseThreads[i].IsAlive)
                {
                    _parseThreads[i] = new Thread(SafeParseLoop)
                    {
                        IsBackground = true,
                        Name = $"Parser-{i}",
                        Priority = ThreadPriority.Normal
                    };
                    _parseThreads[i].Start(i);
                }
            }
        }
    }

    private void PerformanceMonitorLoop()
    {
        while (_isRunning && !_cancellationTokenSource.Token.IsCancellationRequested)
        {
            try
            {
                _cancellationTokenSource.Token.WaitHandle.WaitOne(3000);
                if (!_isRunning) break;

                if (AppConfig.LogPrint == 1)
                {
                    AdjustThreadCount();
                    AdjustQueueCapacity();
                }
            }
            catch (Exception ex)
            {
                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"[性能监控错误] {ex.Message}");
                }
            }
        }
    }

    private void AdjustThreadCount()
    {
        lock (_threadManagementLock)
        {
            var now = DateTime.UtcNow;
            var elapsed = now - _lastMonitorTime;

            if (elapsed.TotalSeconds < 2) return;

            long currentFrames = _totalProcessedFrames;
            double frameRate = (currentFrames - _lastProcessedFrames) / elapsed.TotalSeconds;

            _lastProcessedFrames = currentFrames;
            _lastMonitorTime = now;

            _recentProcessingRates.Enqueue(frameRate);
            if (_recentProcessingRates.Count > 10)
            {
                _recentProcessingRates.Dequeue();
            }

            double avgRate = _recentProcessingRates.Count > 0 ? _recentProcessingRates.Average() : 0;
            int queueDepth = _dataQueue.Count;

            bool shouldIncrease = false;
            bool shouldDecrease = false;

            if (_currentThreadCount < _maxThreads)
            {
                shouldIncrease = (queueDepth > 2000) || (avgRate > 10000 && queueDepth > 500);
            }

            if (_currentThreadCount > _minThreads)
            {
                shouldDecrease = (avgRate < 50 && queueDepth < 100) || (avgRate == 0 && queueDepth == 0);
            }

            if (shouldIncrease)
            {
                int newThreadIndex = _currentThreadCount;
                if (newThreadIndex < _maxThreads)
                {
                    _parseThreads[newThreadIndex] = new Thread(SafeParseLoop)
                    {
                        IsBackground = true,
                        Name = $"Parser-{newThreadIndex}",
                        Priority = ThreadPriority.Normal
                    };
                    _parseThreads[newThreadIndex].Start(newThreadIndex);
                    _currentThreadCount++;
                }
            }
            else if (shouldDecrease)
            {
                _currentThreadCount--;
            }
        }
    }

    private void AdjustQueueCapacity()
    {
        int queueCount = _dataQueue.Count;
        long avgRate = _recentProcessingRates.Count > 0 ? (long)_recentProcessingRates.Average() : 0;

        if (avgRate > 20000 && queueCount < BASE_QUEUE_CAPACITY / 2)
        {
            _currentQueueCapacity = Math.Min(BASE_QUEUE_CAPACITY * 3, 50000);
        }
        else if (avgRate < 1000)
        {
            _currentQueueCapacity = BASE_QUEUE_CAPACITY;
        }
        else
        {
            _currentQueueCapacity = BASE_QUEUE_CAPACITY * 2;
        }
    }
    #endregion

    #region 解析核心
    private void SafeParseLoop(object threadIndexObj)
    {
        int threadIndex = (int)threadIndexObj;
        long localProcessedFrames = 0;
        long localProcessedSamples = 0;
        long localProcessedBytes = 0;
        long localErrors = 0;

        var localResultBatch = new List<ParsedFrameData>(BATCH_SIZE);

        try
        {
            while (_isRunning)
            {
                if (threadIndex >= _currentThreadCount && threadIndex >= _minThreads)
                {
                    break;
                }

                int batchCount = 0;
                while (batchCount < BATCH_SIZE && _dataQueue.TryDequeue(out byte[] data))
                {
                    try
                    {
                        var parseResult = FastParse(data);
                        if (parseResult != null)
                        {
                            localResultBatch.Add(parseResult);
                            localProcessedFrames++;
                            localProcessedSamples += parseResult.TotalSamples;
                            localProcessedBytes += data.Length;
                        }
                        else
                        {
                            localErrors++;
                        }
                    }
                    catch (Exception ex)
                    {
                        localErrors++;
                        if (AppConfig.LogPrint == 1)
                        {
                            Console.WriteLine($"[解析器线程{threadIndex}错误] {ex.Message}");
                        }
                    }
                    batchCount++;
                }

                if (localResultBatch.Count > 0)
                {
                    foreach (var result in localResultBatch)
                    {
                        _resultQueue.Enqueue(result);
                    }
                    localResultBatch.Clear();

                    Interlocked.Add(ref _totalProcessedFrames, localProcessedFrames);
                    Interlocked.Add(ref _totalProcessedSamples, localProcessedSamples);
                    Interlocked.Add(ref _totalProcessedBytes, localProcessedBytes);
                    Interlocked.Add(ref _totalErrors, localErrors);

                    localProcessedFrames = 0;
                    localProcessedSamples = 0;
                    localProcessedBytes = 0;
                    localErrors = 0;
                }

                if (batchCount == 0)
                {
                    Thread.Sleep(1);
                }

                while (_resultQueue.Count > RESULT_QUEUE_CAPACITY)
                {
                    _resultQueue.TryDequeue(out _);
                }
            }
        }
        catch (Exception ex)
        {
            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine($"[解析器线程{threadIndex}致命错误] {ex.Message}");
            }
        }
    }

    private ParsedFrameData FastParse(byte[] data)
    {
        if (data == null || data.Length < HEADER_SIZE + TAIL_SIZE)
        {
            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine($"[解析失败] 数据包长度不足: {data?.Length ?? 0} 字节");
            }
            return null;
        }

        if (AppConfig.LogPrint == 1)
        {
            Console.WriteLine("\n" + new string('=', 80));
            Console.WriteLine("数据包结构解析开始");
            Console.WriteLine(new string('=', 80));
            Console.WriteLine($"数据包总长度: {data.Length} 字节");

            // 显示包头预览（前32字节）
            int previewLength = Math.Min(32, data.Length);
            string hexPreview = string.Join(" ", data.Take(previewLength).Select(b => $"{b:X2}"));
            Console.WriteLine($"包头预览: {hexPreview}{(data.Length > 32 ? "..." : "")}");
        }

        var channels = new List<ParsedChannelData>();
        int totalSamples = 0;
        int totalDeductedPoints = 0;
        long baseTimeTicks = DateTime.UtcNow.Ticks;
        int pos = 0;

        try
        {
            for (int channelNum = MIN_CHANNEL; channelNum <= MAX_CHANNEL; channelNum++)
            {
                if (pos + HEADER_SIZE + STATISTICS_SIZE > data.Length - TAIL_SIZE)
                {
                    if (AppConfig.LogPrint == 1)
                    {
                        Console.WriteLine($"[解析结束] 位置{pos}: 剩余数据不足，停止解析");
                    }
                    break;
                }

                // 检查起始帧
                if (data[pos] != FRAME_HEADER || data[pos + 1] != channelNum)
                {
                    if (AppConfig.LogPrint == 1)
                    {
                        Console.WriteLine($"[跳过] 位置{pos}: 未找到通道{channelNum}起始帧 (期望:0x5A{channelNum:02X}, 实际:0x{data[pos]:X2}{data[pos + 1]:X2})");
                    }
                    break;
                }

                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"\n通道 {channelNum} (0x5A{channelNum:02X}) [位置:{pos}]:");
                }
                pos += HEADER_SIZE;

                // 通道1特殊处理
                if (channelNum == 1)
                {
                    if (AppConfig.LogPrint == 1)
                    {
                        Console.WriteLine($"[解析] 通道1(干扰通道): 扣除点数=0");
                    }

                    var channel1Data = new ParsedChannelData
                    {
                        ChannelNumber = 0, // 显示为通道0
                        Statistics = 0,    // 干扰通道扣除点固定为0
                        TimestampTicks = baseTimeTicks,
                        IsEmpty = true,
                        SampleCount = 0,
                        Samples = new AdcSample[0]
                    };

                    channels.Add(channel1Data);
                    continue;
                }
                // 处理通道2-8：读取扣除点数
                if (pos + 4 > data.Length)
                    break;

                // 确保按大端序读取扣除点数
                uint deductionCount = (uint)data[pos] << 24 |
                    (uint)data[pos + 1] << 16 |
                    (uint)data[pos + 2] << 8 |
                    data[pos + 3];

                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"[解析] 通道{channelNum}: 扣除点数原始字节=[{data[pos]:X2} {data[pos + 1]:X2} {data[pos + 2]:X2} {data[pos + 3]:X2}] => {deductionCount}");
                }

                pos += STATISTICS_SIZE;

                int dataEndPos = FindNextChannelOrTailSafe(data, pos, channelNum + 1);
                int availableDataLength = dataEndPos - pos;

                int displayChannelNumber = channelNum - 1; // 物理通道2-8 -> 显示通道1-7

                var channelData = new ParsedChannelData
                {
                    ChannelNumber = displayChannelNumber,
                    Statistics = deductionCount, // 确保扣除点数被正确设置
                    TimestampTicks = baseTimeTicks
                };

                bool shouldParseData = ShouldParseChannelDataForParsing(channelNum, availableDataLength);

                if (!shouldParseData)
                {
                    if (AppConfig.LogPrint == 1)
                    {
                        Console.WriteLine($"  -> 通道{channelNum}不需要解析数据 (IsHighEnd:{IsHighEndVersion})");
                    }
                    channelData.IsEmpty = true;
                    channelData.SampleCount = 0;
                    channelData.Samples = new AdcSample[0];
                }
                else
                {
                    int sampleCount = Math.Min(availableDataLength / SAMPLE_SIZE, 50000);
                    if (AppConfig.LogPrint == 1)
                    {
                        Console.WriteLine($"  数据点数: {sampleCount}");
                    }

                    channelData.IsEmpty = false;
                    channelData.SampleCount = sampleCount;
                    channelData.Samples = new AdcSample[sampleCount];

                    // 解析ADC数据并统计
                    var voltages = new List<double>();
                    var adcValues = new List<ushort>();

                    SafeConvertSamplesWithLog(data, pos, sampleCount, channelData.Samples, baseTimeTicks, voltages, adcValues);

                    // 统计信息
                    if (voltages.Count > 0 && AppConfig.LogPrint == 1)
                    {
                        double minVoltage = voltages.Min();
                        double maxVoltage = voltages.Max();
                        double voltageRange = maxVoltage - minVoltage;

                        Console.WriteLine($"  电压范围: {minVoltage:F4}V ~ {maxVoltage:F4}V (范围:{voltageRange:F4}V)");

                        // 显示前3个数据点
                        if (voltages.Count >= 3)
                        {
                            Console.Write("  前3个数据点: ");
                            for (int i = 0; i < Math.Min(3, voltages.Count); i++)
                            {
                                Console.Write($"ADC:{adcValues[i]}({voltages[i]:F4}V) ");
                            }
                            Console.WriteLine();
                        }

                        // 显示最大最小值位置
                        int minIdx = voltages.IndexOf(minVoltage);
                        int maxIdx = voltages.IndexOf(maxVoltage);
                        Console.WriteLine($"  最小值: ADC:{adcValues[minIdx]}({minVoltage:F4}V) [位置:{minIdx + 1}]");
                        Console.WriteLine($"  最大值: ADC:{adcValues[maxIdx]}({maxVoltage:F4}V) [位置:{maxIdx + 1}]");
                    }

                    totalSamples += sampleCount;
                }

                channels.Add(channelData);
                pos = dataEndPos;
            }

            // 验证帧尾
            bool hasValidTail = false;
            if (pos + 1 < data.Length && data[pos] == FRAME_TAIL_BYTE1 && data[pos + 1] == FRAME_TAIL_BYTE2)
            {
                hasValidTail = true;
                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"\n找到帧尾: 0x{FRAME_TAIL_BYTE1:X2}{FRAME_TAIL_BYTE2:X2} (位置: {pos})");
                }
            }
            else
            {
                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"\n[警告] 未找到有效帧尾 (位置:{pos}, 期望:0x0D0A, 实际:0x{(pos < data.Length ? data[pos] : 0):X2}{(pos + 1 < data.Length ? data[pos + 1] : 0):X2})");
                }
            }

            // 输出解析统计总结
            if (AppConfig.LogPrint == 1)
            {
                PrintParseStatisticsSummary(channels, totalSamples, totalDeductedPoints, data.Length);
            }

            if (hasValidTail)
            {
                // 在返回结果前添加验证日志
                if (channels.Count > 0 && AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"[解析完成] 解析出{channels.Count}个通道：");
                    foreach (var ch in channels)
                    {
                        Console.WriteLine($"  显示通道{ch.ChannelNumber}: 扣除点={ch.Statistics}, 采样数={ch.SampleCount}");
                    }
                }

                return new ParsedFrameData
                {
                    Channels = channels.ToArray(),
                    ChannelCount = channels.Count,
                    ParseTimeTicks = DateTime.UtcNow.Ticks,
                    TotalSamples = totalSamples,
                    IsHighEndVersion = IsHighEndVersion
                };
            }

            return null;
        }
        catch (Exception ex)
        {
            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine($"[解析异常] {ex.Message}");
                Console.WriteLine($"异常位置: {pos}, 数据长度: {data.Length}");
            }
            return null;
        }
    }


    private void PrintParseStatisticsSummary(List<ParsedChannelData> channels, int totalSamples, int totalDeductedPoints, int packetLength)
    {
        Console.WriteLine("\n" + new string('-', 88));
        Console.WriteLine("通道统计总结");
        Console.WriteLine(new string('-', 88));
        Console.WriteLine($"{"通道",-4} {"扣除点",-8} {"数据点",-8} {"数据字节",-10} {"最小电压",-12} {"最大电压",-12} {"电压范围",-12}");
        Console.WriteLine(new string('-', 88));

        foreach (var channel in channels)
        {
            if (channel.IsEmpty)
            {
                Console.WriteLine($"{channel.ChannelNumber,-4} {channel.Statistics,-8} {"0",-8} {"0",-10} {"N/A",-12} {"N/A",-12} {"N/A",-12}");
            }
            else if (channel.Samples != null && channel.SampleCount > 0)
            {
                var voltages = channel.Samples.Take(channel.SampleCount).Select(s => (double)s.Voltage).ToArray();
                double minVoltage = voltages.Min();
                double maxVoltage = voltages.Max();
                double voltageRange = maxVoltage - minVoltage;
                int dataBytes = channel.SampleCount * 2;

                Console.WriteLine($"{channel.ChannelNumber,-4} {channel.Statistics,-8} {channel.SampleCount,-8} {dataBytes,-10} " +
                                 $"{minVoltage,-12:F4} {maxVoltage,-12:F4} {voltageRange,-12:F4}");
            }
        }

        Console.WriteLine(new string('-', 88));
        Console.WriteLine($"总计: 扣除点={totalDeductedPoints}, 数据点={totalSamples}, 包长度={packetLength}字节");
        Console.WriteLine(new string('=', 88));
    }


    //private void SafeConvertSamplesWithLog(byte[] sourceData, int startPos, int sampleCount,
    //AdcSample[] targetSamples, long baseTimeTicks, List<double> voltages, List<ushort> adcValues)
    //{
    //    int pos = startPos;
    //    int errorCount = 0;

    //    for (int i = 0; i < sampleCount && pos + SAMPLE_SIZE <= sourceData.Length; i++)
    //    {
    //        try
    //        {
    //            // 大端序读取无符号16位整数
    //            ushort rawValue = (ushort)((sourceData[pos] << 8) | sourceData[pos + 1]);
    //            pos += SAMPLE_SIZE;

    //            // 使用协议规定的电压转换公式：ADC值 × 3.0 ÷ 65535
    //            double voltage = rawValue * 3.0 / 16384;

    //            targetSamples[i] = new AdcSample
    //            {
    //                RawValue = rawValue, // 如果结构体要求short类型
    //                Voltage = (float)voltage,
    //                TimestampTicks = baseTimeTicks + (long)(i * _sampleIntervalTicks),
    //                SampleIndex = i
    //            };

    //            voltages.Add(voltage);
    //            adcValues.Add(rawValue);

    //            // 记录异常值
    //            if (voltage < 0 || voltage > 3.0)
    //            {
    //                if (AppConfig.LogPrint == 1)
    //                {
    //                    Console.WriteLine($"    [警告] 采样点{i}: ADC={rawValue}, 电压={voltage:F4}V 超出正常范围[0V-3V]");
    //                }
    //            }
    //        }
    //        catch (Exception ex)
    //        {
    //            errorCount++;
    //            if (AppConfig.LogPrint == 1)
    //            {
    //                Console.WriteLine($"    [错误] 采样点{i}转换失败: {ex.Message}");
    //                if (errorCount > 10) // 避免过多错误日志
    //                {
    //                    Console.WriteLine($"    [错误] 转换错误过多，停止记录错误日志");
    //                    break;
    //                }
    //            }
    //        }
    //    }

    //    if (errorCount > 0 && AppConfig.LogPrint == 1)
    //    {
    //        Console.WriteLine($"  -> 转换完成，共{errorCount}个错误");
    //    }
    //}

    private void SafeConvertSamplesWithLog(byte[] sourceData, int startPos, int sampleCount,
    AdcSample[] targetSamples, long baseTimeTicks, List<double> voltages, List<ushort> adcValues)
    {
        int pos = startPos;
        int errorCount = 0;
        for (int i = 0; i < sampleCount && pos + SAMPLE_SIZE <= sourceData.Length; i++)
        {
            try
            {
                // 大端序读取无符号16位整数
                ushort rawValue = (ushort)((sourceData[pos] << 8) | sourceData[pos + 1]);
                pos += SAMPLE_SIZE;

                // 修改后的电压转换公式：双极性范围 -1.75V 到 +1.75V
                // 14位ADC: 0→-1.75V, 8192→0V, 16383→+1.75V
                // 逆向公式：voltage = (rawValue * 3.5 / 16384) - 1.75
                double voltage = rawValue * 3.5 / 16384.0 - 1.75;

                targetSamples[i] = new AdcSample
                {
                    RawValue = rawValue, // 如果结构体要求short类型
                    Voltage = (float)voltage,
                    TimestampTicks = baseTimeTicks + (long)(i * _sampleIntervalTicks),
                    SampleIndex = i
                };

                voltages.Add(voltage);
                adcValues.Add(rawValue);

                // 记录异常值 - 修改为新的电压范围检查
                if (voltage < -1.75 || voltage > 1.75)
                {
                    if (AppConfig.LogPrint == 1)
                    {
                        Console.WriteLine($"    [警告] 采样点{i}: ADC={rawValue}, 电压={voltage:F4}V 超出正常范围[-1.75V~+1.75V]");
                    }
                }
            }
            catch (Exception ex)
            {
                errorCount++;
                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"    [错误] 采样点{i}转换失败: {ex.Message}");
                    if (errorCount > 10) // 避免过多错误日志
                    {
                        Console.WriteLine($"    [错误] 转换错误过多，停止记录错误日志");
                        break;
                    }
                }
            }
        }
        if (errorCount > 0 && AppConfig.LogPrint == 1)
        {
            Console.WriteLine($"  -> 转换完成，共{errorCount}个错误");
        }
    }



    private int FindNextChannelOrTailSafe(byte[] data, int startPos, int nextChannelNum)
    {
        if (nextChannelNum > MAX_CHANNEL)
        {
            for (int i = startPos; i < data.Length - 1; i++)
            {
                if (data[i] == FRAME_TAIL_BYTE1 && data[i + 1] == FRAME_TAIL_BYTE2)
                {
                    return i;
                }
            }
            return Math.Max(startPos, data.Length - TAIL_SIZE);
        }

        for (int i = startPos; i < data.Length - HEADER_SIZE; i++)
        {
            if (data[i] == FRAME_HEADER && data[i + 1] == nextChannelNum)
            {
                return i;
            }
        }

        return Math.Max(startPos, data.Length - TAIL_SIZE);
    }

    private bool ShouldParseChannelDataForParsing(int physicalChannelNum, int availableDataLength)
    {
        if (availableDataLength <= 0)
            return false;

        if (IsHighEndVersion)
        {
            if (physicalChannelNum == 1)
            {
                return false;
            }
            else if (physicalChannelNum >= 2 && physicalChannelNum <= MAX_CHANNEL)
            {
                int displayChannel = physicalChannelNum - 1;
                return displayChannel < SelectedChannels.Length && SelectedChannels[displayChannel];
            }
            return false;
        }
        else
        {
            return physicalChannelNum < SelectedChannels.Length && SelectedChannels[physicalChannelNum];
        }
    }

    private int GetDisplayChannelNumber(int physicalChannelNum)
    {
        if (IsHighEndVersion)
        {
            // 物理通道1是干扰通道，通常不在业务层显示
            // 物理通道2-8 映射到 业务通道1-7
            if (physicalChannelNum == 1)
            {
                return 0; // 干扰通道，标记为0或者特殊值
            }
            else if (physicalChannelNum >= 2 && physicalChannelNum <= 8)
            {
                return physicalChannelNum - 1; // 物理通道2->业务通道1, 物理通道3->业务通道2, etc.
            }
        }
        return physicalChannelNum;
    }

    // 修改SafeConvertSamples方法
    private void SafeConvertSamples(byte[] sourceData, int startPos, int sampleCount, AdcSample[] targetSamples, long baseTimeTicks)
    {
        int pos = startPos;

        for (int i = 0; i < sampleCount && pos + SAMPLE_SIZE <= sourceData.Length; i++)
        {
            // 按大端序读取无符号16位整数
            ushort rawValue = (ushort)((sourceData[pos] << 8) | sourceData[pos + 1]);
            pos += SAMPLE_SIZE;

            targetSamples[i] = new AdcSample
            {
                RawValue = rawValue,  // 如果结构体需要保持short，强制转换
                Voltage = rawValue * _lsbFloat,  // 简化公式：ADC值 × 3.0 ÷ 65535
                TimestampTicks = baseTimeTicks + (long)(i * _sampleIntervalTicks),
                SampleIndex = i
            };
        }
    }
    #endregion

    #region 性能监控
    private void PrintFinalStats()
    {
        long endTicks = DateTime.UtcNow.Ticks;
        double totalSeconds = (endTicks - _startTimeTicks) / (double)TimeSpan.TicksPerSecond;

        Console.WriteLine("=== 解析器最终性能统计 ===");
        Console.WriteLine($"[总计] 运行时间: {totalSeconds:F3}秒");
        Console.WriteLine($"[总计] 处理帧数: {_totalProcessedFrames:N0}");
        Console.WriteLine($"[总计] 处理采样点: {_totalProcessedSamples:N0}");
        Console.WriteLine($"[总计] 处理字节: {_totalProcessedBytes / 1024.0 / 1024.0:F2} MB");

        if (totalSeconds > 0)
        {
            Console.WriteLine($"[平均] 帧处理速率: {_totalProcessedFrames / totalSeconds:F0} fps");
            Console.WriteLine($"[平均] 采样处理速率: {_totalProcessedSamples / totalSeconds:F0} sps");
            Console.WriteLine($"[平均] 数据处理速率: {(_totalProcessedBytes / 1024.0 / 1024.0) / totalSeconds:F2} MB/s");
        }

        Console.WriteLine($"[错误] 总错误数: {_totalErrors}");
        Console.WriteLine($"[线程] 最终线程数: {_currentThreadCount}");
        Console.WriteLine("===============================");
    }
    #endregion

    #region 资源释放
    public void Dispose()
    {
        if (_disposed) return;

        lock (_disposeLock)
        {
            if (!_disposed)
            {
                Stop();
                _cancellationTokenSource?.Dispose();

                while (_dataQueue.TryDequeue(out _)) { }
                while (_resultQueue.TryDequeue(out _)) { }

                _disposed = true;
                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine("[释放] 解析器资源已释放");
                }
            }
        }
    }
    #endregion
}